/*
 * @lc app=leetcode.cn id=18 lang=cpp
 *
 * [18] 四数之和
 */

// @lc code=start
class Solution
{
public:
    vector<vector<int>> fourSum(vector<int> &nums, int target)
    {
        //四数之和 其实和三数之和差不多 只不过多了一层循环而已
        vector<vector<int>> res;
        int n = nums.size();
        if (n < 3)
        {
            return res;
        }
        sort(nums.begin(), nums.end());
        for (int i = 0; i < n - 3; i++)
        {
            //剪枝
            if (nums[i] > target)
            {
                return res;
            }
            if (i > 0 && nums[i] == nums[i - 1])
            {
                continue;
            }
            for (int j = i + 1; j < n - 2; j++)
            {
                if (j > i + 1 && nums[j] == nums[j - 1])
                {
                    continue;
                }
                int left = j + 1;
                int right = n - 1;
                while (left < right)
                {
                    if (nums[left] + nums[right] > target - nums[i] - nums[j])
                    {
                        right--;
                        
                    }
                    else if (nums[left] + nums[right] < target - nums[i] - nums[j])
                    {
                        left++;
                        while (left < right && nums[left] == nums[left - 1])
                        {
                            left++;
                        }
                    }
                    else
                    {
                        res.push_back({nums[i], nums[j], nums[left], nums[right]});
                        while (left < right && nums[right] == nums[right + 1])
                        {
                            right--;
                        }
                    }
                }
            }
        }
        return res;
    }
};
// @lc code=end
